#include <iostream>
#include <cstring>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>

// ./client_tcp serverip serverport
int main(int argc, char* argv[])
{
    if (argc != 3)
    {
        std::cout << "Usage: " << argv[0] << " serverip serverport" << std::endl;
        return 1;
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);   
     
    int sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        std::cout << "create socket failed" << std::endl;
        return 2;
    } 

    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = ::htons(serverport);
    server.sin_addr.s_addr = ::inet_addr(serverip.c_str());

    int n = ::connect(sockfd, (const struct sockaddr*)&server, sizeof(server));
    if (n < 0)
    {
        std::cout << "connect failed" << std::endl;
        return 3;
    }
    
    while (1)
    {
        std::cout << "Please Enter@ ";
        std::string message;
        std::getline(std::cin, message);
        n = ::write(sockfd, message.c_str(), message.size());
        if (n > 0)
        {
            char buffer[4096];
            int m = ::read(sockfd, buffer, sizeof(buffer) - 1);
            if (m > 0)
            {
                buffer[m] = 0;
                std::cout << buffer << std::endl;
            }
            else break;
        }
        else break;
    }

    return 0;
}